#!/usr/bin/env python

# Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Street Identity Temporary API - Registration and De-Registration for APs."""
import cgi

from base import BaseHandler
from lib import authz, scope_utils, scope_manager
from lib.loggable import loggable
import model

__author__ = 'Maciej Machulak'
__maintainer__ = 'Maciej Machulak'
__email__ = 'mmachulak@google.com'

__copyright__ = 'Copyright 2012, Google Inc.'
__license__ = 'Apache License 2.0'
__version__ = '0.2'
__status__ = 'Prototype'

_STREETIDENTITY_SCOPES_WRITE = [
    'https://www.googleapis.com/auth/streetidentity.write',
    'https://www.googleapis.com/auth/verifiedage.write',
    'https://www.googleapis.com/auth/verifiedgender.write']

def _filter_streetidentity_scopes(scopes):
  """Returns a list of street identity scopes."""

  si_scopes = []
  for scope in scopes:
    if scope in _STREETIDENTITY_SCOPES_WRITE:
      si_scopes.append(scope)
  return si_scopes


class RegistrationHandler(BaseHandler):
  """Registers an application as Attribute Provider for a user."""

  @authz.api_authz_required(scopes=_STREETIDENTITY_SCOPES_WRITE)
  @loggable('registers application as attribute provider for user')
  def post(self):
    """Handles POST requests and registers application as AP."""

    user = self.user
    application = self.application

    # Try to update the application
    app_name = cgi.escape(self.request.get('name', ''))
    app_icon_url = cgi.escape(self.request.get('icon_url', ''))
    app_url = cgi.escape(self.request.get('url', ''))

    updated = False
    if app_name:
      application.name = app_name
      updated = True
    if app_icon_url:
      application.icon_url = app_icon_url
      updated = True
    if app_url:
      application.url = app_url
      updated = True

    if updated:
      application.put()

    si_scopes = scope_utils.filter_scopes(self.scopes, _STREETIDENTITY_SCOPES_WRITE)
    all_si_scopes=  scope_manager.get_dependent_scopes(si_scopes)

    ap = model.AttributeProvider.all()\
        .filter('application = ', application)\
        .filter('user = ', user)\
        .get()

    status_code = 204
    if ap is None:

      ap = model.AttributeProvider(application = application,
                                   user = user,
                                   scopes = all_si_scopes)
      ap.put()
      status_code = 200

    if updated:
      status_code = 200
    self.response.set_status(status_code)
    return


class DeRegistrationHandler(BaseHandler):
  """Removes an application as Attribute Provider for a user."""

  @authz.api_authz_required(scopes=_STREETIDENTITY_SCOPES_WRITE)
  @loggable('removes application as attribute provider for user')
  def post(self):
    """Handles POST requests and removes application as AP."""

    user = self.user
    application = self.application

    ap = model.AttributeProvider.all()\
        .filter('application = ', application)\
        .filter('user = ', user)\
        .get()

    if ap:
      ap.delete()
      self.response.set_status(200)
      return

    # TODO(mmachulak) correct code?
    self.response.set_status(403)
    return
